package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author atguigu-mqx
 * @ClassName UserAccountReceiver
 * @description: TODO
 * @date 2024年12月28日
 * @version: 1.0
 */
@Component
public class UserAccountReceiver {

    @Autowired
    private UserAccountService userAccountService;


    //  消息队列！ 初始化绑定关系；第一种直接写注解；第二种：编写配置类！
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void register(Long userId, Message message , Channel channel){
        System.out.println("用户注册成功！");
        try {
            if (null != userId){
                //  调用服务层方法
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            //  由于网络异常-消息重回队列
            //  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //  非网络异常- 利用redis进行重试消费(3次)，如果依然失败：记录异常消息表！
            System.out.println(e.getMessage());
        }

        //  手动确认 -- 能够非常清楚的了解业务是否处理成功！
        try {
            //  业务正确处理！
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
